<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        size="small"
        v-perm="'ecoupon-activity:add'"
        v-waves
        icon="el-icon-plus"
        @click="handleUpdate(null)"
      >添加</el-button>
      <el-input
        @keyup.enter.native="handleFilter"
        size="small"
        style="width: 200px;"
        class="filter-item"
        clearable
        placeholder="活动名称"
        v-model="params.activityName"
      ></el-input>
      <el-select size="small" v-model="params.checkStatus">
        <el-option
          v-for="(text,value) in checkStatusEnums"
          :key="value"
          :value="value"
          :label="text"
        ></el-option>
      </el-select>
      <el-date-picker
        v-model="params.createTimeStart"
        :picker-options="datePickerOptions1"
        clearable
        class="filter-item"
        size="small"
        value-format="yyyy-MM-dd"
        type="date"
        placeholder="创建时间--开始时间"
      />
      <el-date-picker
        v-model="params.createTimeEnd"
        :picker-options="datePickerOptions1"
        size="small"
        class="filter-item"
        value-format="yyyy-MM-dd"
        clearable
        type="date"
        placeholder="创建时间——截止时间"
      />
      <el-button
        class="filter-item"
        type="primary"
        size="small"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="primary"
        size="small"
        v-perm="'ecoupon-activity:edit'"
        v-waves
        icon="el-icon-document"
        @click="exportExcelFile"
      >导出</el-button>
      <!-- <div
        style="display:inline-block;margin-left:10px;vertical-align:middle;"
        v-if="~accessable.indexOf('goods_brand:batch_import')"
      >
        <el-upload
          class="upload-demo"
          action="/admin/goods_brand/import"
          :on-success="onImportSuccess"
          :limit="1"
          :show-file-list="false"
        >
          <el-button icon="el-icon-document" size="small" type="primary">导入</el-button>
        </el-upload>
      </div>-->
      <!-- <el-button
        icon="el-icon-document"
        size="small"
        type="primary"
        @click="downloadFile()"
      >商品品牌批量导入模板下载</el-button>-->
    </div>
    <el-table
      :data="list"
      :height="tableHeight"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <!-- <el-table-column align="center" type="index" label="序号" width="80"></el-table-column> -->
      <el-table-column prop="activityName" align="center" label="活动名称" width="140" fixed="left"></el-table-column>
      <el-table-column align="center" label="活动开始时间" width="170" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.row.startTime|parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="活动结束时间" width="170" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.row.endTime|parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="120" fixed="left">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.checkStatus|checkStatusTagFilter"
          >{{scope.row.checkStatus|checkStatusFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.checkTime|parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核备注" width="170" prop="checkRemark"></el-table-column>
      <el-table-column align="center" label="标签用户才可领取" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.limitLabelFlag|yesNoFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="活动链接地址" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.activityUrl}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.createTime|parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建用户" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.creator}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="修改时间" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.modifyTime|parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="修改人" width="170">
        <template slot-scope="scope">
          <span>{{scope.row.modifier}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            v-perm="'ecoupon-activity:edit'"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            type="primary"
            size="mini"
            v-perm="'ecoupon-activity:resolve'"
            @click="handleResolve(scope.row)"
          >审核通过</el-button>
          <el-button
            type="danger"
            size="mini"
            v-perm="'ecoupon-activity:reject'"
            @click="handleReject(scope.row)"
          >审核拒绝</el-button>
          <!-- <el-button
            size="mini"
            type="danger"
            v-perm="'ecoupon-activity:delete'"
            @click="handleDelete(scope.row)"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.pageNo"
        :page-sizes="[10,20,30,50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible">
      <el-form
        class="dialog-form"
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="temp.activityName" placeholder="活动名称不能超过20个字符"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动开始时间" prop="startTime">
              <el-date-picker
                v-model="temp.startTime"
                :picker-options="datePickerOptions1"
                clearable
                class="filter-item"
                size="small"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="活动开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动结束时间" prop="endTime">
              <el-date-picker
                v-model="temp.endTime"
                :picker-options="datePickerOptions1"
                clearable
                class="filter-item"
                size="small"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="活动结束时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="电子券号" prop="couponNo">
          <el-input
            v-model="temp.couponNo"
            type="textarea"
            :rows="4"
            placeholder="电子券号，多个电子券号以逗号分隔"
          />
        </el-form-item>
        <el-form-item label="标签用户才可领取" prop="limitLabelFlag">
          <el-switch v-model="temp.limitLabelFlag" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="会员标签" prop="labelList" v-if="temp.limitLabelFlag==1">
          <el-checkbox-group v-model="temp.labelList">
            <el-checkbox v-for="item in labelList" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '../../filters';
const checkStatusEnums = {
  0: '待审核',
  5: '审核通过',
  10: '审核驳回'
}
export default {
  data () {
    return {
      tableHeight: 400,
      total: 0,
      checkStatusEnums,
      datePickerOptions1: {
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      temp: {
        id: '',
        activityName: '',
        labelList: [],
        startTime: '',
        endTime: '',
        limitLabelFlag: '',
        couponNo: ''
      },
      params: {
        pageSize: 10,
        pageNo: 1
      },
      labelList: [],
      rules: {
        labelList: [
          {
            required: true,
            type: 'array',
            message: '请选择至少一个会员标签',
            trigger: 'change'
          }
        ],
        limitLabelFlag: [
          {
            required: true,
            message: '请选择仅标签会员可见',
            trigger: 'change'
          }
        ],
        couponNo: [
          {
            required: true,
            message: '请输入电子券号',
            trigger: 'change'
          }
        ],
        startTime: [
          {
            required: true,
            message: '活动开始时间不能为空',
            trigger: 'change'
          }
        ],

        endTime: [
          {
            required: true,
            message: '活动结束时间不能为空',
            trigger: 'change'
          }
        ],
        activityName: [
          {
            required: true,
            message: '活动名称不能为空',
            trigger: 'change'
          },
          {
            max: 20,
            message: '活动名称不能超过20个字符',
            trigger: 'change'
          }
        ],
        sort: [
          {
            required: true,
            message: '显示顺序不能为空',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created () {
    // this.init('ecoupon_activity', 1)
    // this.setFilterAsPostParam(true)
    this.loadData()
    this.tableHeight = window.innerHeight - 300
    this.$get('/admin/goods_theme/label_list').then(data => {
      this.labelList = data
    })
  },
  filters: {
    checkStatusFilter (v) {
      return checkStatusEnums[v]
    },
    checkStatusTagFilter (v) {
      if (v == 5) {
        return 'primary';
      } else if (v == 10) {
        return 'danger';
      } else {
        return 'info';
      }
    }
  },
  methods: {
    findNameByLabelId (id) {
      let rt = '';
      this.labelList.every(el => {
        if (el.id === id) {
          rt = el.name
          return false
        }
        return true
      })
      return rt
    },
    submitFormAction () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          let func = null
          if (!this.isEditing) {
            func = '/admin/ecoupon_activity/add';
          } else {
            func = '/admin/ecoupon_activity/modify';
          }
          const postData = {
            ...this.temp,
            couponNo: this.temp.couponNo
              .trim()
              .split(',')
              .map(el => el.trim())
          }
          let idx = 0
          this.temp.labelList.forEach(el => {
            if (
              this.labelList.some(c => {
                return c.id === el
              })
            ) {
              postData[`labelList[${idx}].labelId`] = el
              postData[`labelList[${idx}].labelName`] = this.findNameByLabelId(
                el
              )
              idx++
            }
          })
          delete postData.labelList
          this.$post(func, postData)
            .then(() => {
              this.submiting = false
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.loadData()
            })
            .catch(info => {
              this.submiting = false
            })
        }
      })
    },
    handleResolve (row) {
      this.$prompt('审核备注', '确认审核通过吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.$post('/admin/ecoupon_activity/check', {
            id: row.id,
            checkResult: 1,
            checkRemark: value
          }).then(data => {
            this.$$notify('审核通过成功')
            this.loadData()
          })
        })
        .catch(() => {})
    },
    handleReject (row) {
      this.$prompt('审核备注', '确认审核拒绝吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.$post('/admin/ecoupon_activity/check', {
            id: row.id,
            checkResult: 0,
            checkRemark: value
          }).then(data => {
            this.$$notify('审核拒绝成功')
            this.loadData()
          })
        })
        .catch(() => {})
    },
    downloadFile () {
      let url = '/excels/商品品牌批量导入模板.xlsx';
      this.openWin(url)
    },
    handleFilter () {
      this.params.pageNo = 1
      this.loadData()
    },

    loadData () {
      this.listLoading = true
      this.$post('/admin/ecoupon_activity/list', this.params)
        .then(info => {
          this.listLoading = false
          this.list = info.rows
          if (this.list && this.list.length) {
            this.list.forEach(el => {
              el.couponNo = el.couponList
                ? el.couponList.map(el => el.couponNo).join(',')
                : '';
              el.labelList &&
                (el.labelList = el.labelList.map(i => {
                  return i.labelId
                }))
              el.startTime = parseTime(el.startTime)
              el.endTime = parseTime(el.endTime)
            })
          }
          this.total = info.total
        })
        .catch(res => {
          this.listLoading = false
        })
    },
    onImportSuccess (res, file, list) {
      list.length = 0
      if (res.errcode === 1) {
        this.$message.error(res.msg)
        return;
      }
      this.$$notify('导入成功')
    },
    exportExcelFile () {
      // this.exportExcel({
      //   title: '商品品牌',
      //   fields: [
      //     // {field:'logo',title:'名牌Logo'}
      //     // ,
      //     {
      //       field: 'title',
      //       title: '品牌名称'
      //     },
      //     {
      //       field: 'urlAlias',
      //       title: 'URL重写'
      //     },
      //     {
      //       field: 'sort',
      //       title: '显示顺序'
      //     }
      //   ]
      // }).then(info => {
      //   this.openWin(info)
      // })
      this.$post('/admin/ecoupon_activity/export', this.params).then(info => {
        this.openWin(info)
      })
    }
  }
}
</script>

<style scoped>
.avatar {
  width: 100px;
  display: block;
  margin: 0 auto;
  height: 100px;
}
</style>
